import {
  ConditionUnit,
  getPairsKeyValues,
  getWherePartFromConditionUnits,
  KeyValuePairs,
  SqlDataType
} from "./SqlUtil";


export function getSetUnitSql(unit: string): string {
  return `${unit} = ?`;
}

/**
 * 返回sql的WherePart 以及 参数数组
 * 如果没有条件,WherePart是空字符串.
 * @param setPairs 需要更新的数据
 * @returns
 * 没有条件,返回空字符串,
 * 有条件,返回 `WHERE key1 = ? AND key2 = ?`
 */
export function getSetPartFromSetUnits(setPairs: KeyValuePairs): [string, SqlDataType[]] {
  if (!setPairs.size) {
    return ["", []];
  }
  const [keys, values] = getPairsKeyValues(setPairs)
  let setsString: string = keys.map((_key) => getSetUnitSql(_key)).join(" , ");
  const setPart = `SET ${setsString}`;
  return [setPart, values];
}

export function generateUpdateSqlAndArgs(tableName: string, setPairs: KeyValuePairs, whereConditions: ConditionUnit[]): [string, SqlDataType[]] {
  const sqlHeader: string = `UPDATE ${tableName}`;
  const [setPart, setValues] = getSetPartFromSetUnits(setPairs);
  const [wherePart, whereValues] = getWherePartFromConditionUnits(whereConditions);
  const args: SqlDataType[] = [];
  args.push(...setValues, ...whereValues);
  const sql = `${sqlHeader} ${setPart} ${wherePart}`;
  return [sql, args];
}